package cn.ijero.floatwindow

import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import androidx.core.view.isVisible
import cn.ijero.floatwindow.databinding.LayoutWindowBinding
import kotlin.concurrent.thread

class FloatService : Service() {

    companion object {
        private const val TAG = "FloatService"
        var playPosition = -1
        private const val KEY_POSITION = "POSITION"
        private const val KEY_IS_PLAYING = "IS_PLAYING"
        var isRunning = false
        var isPlaying = false

        @JvmStatic
        fun start(context: Context, position: Int, isPlaying: Boolean) {
            val intent =
                Intent(context, FloatService::class.java)
                    .putExtra(KEY_POSITION, position)
                    .putExtra(KEY_IS_PLAYING, isPlaying)
            context.startService(intent)
        }

        @JvmStatic
        fun stop(context: Context) {
            context.stopService(Intent(context, FloatService::class.java))
        }
    }

    private val windowManager by lazy {
        getSystemService(WindowManager::class.java)
    }
    private val layoutInflater by lazy {
        getSystemService(LayoutInflater::class.java)
    }
    private val binding by lazy {
        LayoutWindowBinding.inflate(layoutInflater)
    }
    private lateinit var layoutParams: WindowManager.LayoutParams

    private var position = 0

    private lateinit var thread: Thread

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        isRunning = true
        position = intent.getIntExtra(KEY_POSITION, 0)
        isPlaying = intent.getBooleanExtra(KEY_IS_PLAYING, false)
        initView()
        return super.onStartCommand(intent, flags, startId)
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initView() {
        val typePhone = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            WindowManager.LayoutParams.TYPE_PHONE
        }
        layoutParams = WindowManager.LayoutParams(
            260.dpInt,
            180.dpInt,
            typePhone,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )
        windowManager.addView(
            binding.root,
            layoutParams
        )

        binding.apply {
            root.setOnTouchListener(FloatTouchListener())
            root.setOnClickListener {
                if (videoView.isPlaying) {
                    videoView.pause()
                    playImageView.isVisible = true
                }
            }
            playImageView.setOnClickListener {
                if (!videoView.isPlaying) {
                    videoView.start()
                    playImageView.isVisible = false
                }
            }

            closeImageView.setOnClickListener {
                val intent = Intent(this@FloatService, MainActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                startActivity(intent)
                stopSelf()
            }
            videoView.setVideoPath("android.resource://${packageName}/${R.raw.video}")
            videoView.seekTo(position)
            playImageView.isVisible = !isPlaying
            if (isPlaying) {
                videoView.start()
            } else {
                videoView.pause()
            }

            thread = thread {
                while (isRunning) {
                    playPosition = videoView.currentPosition
                    Thread.sleep(1000)
                }
            }
        }
    }

    inner class FloatTouchListener : View.OnTouchListener {
        private var rawX = 0f
        private var rawY = 0f

        override fun onTouch(v: View?, event: MotionEvent): Boolean {
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    // 按下事件
                    rawX = event.rawX
                    rawY = event.rawY
                }
                MotionEvent.ACTION_MOVE -> {
                    // 触摸移动事件
                    val disX = event.rawX - rawX
                    val disY = event.rawY - rawY
                    rawX = event.rawX
                    rawY = event.rawY

                    layoutParams.x += disX.toInt()
                    layoutParams.y += disY.toInt()
                    windowManager.updateViewLayout(binding.root, layoutParams)
                    Log.d(TAG, "initView: disX=$disX , disY=$disY")
                }
                MotionEvent.ACTION_UP -> {
                    // 松开事件
                }
                else -> {
                }
            }


            return false
        }


    }

    override fun onDestroy() {
        super.onDestroy()
        windowManager.removeView(binding.root)
        isRunning = false
    }

}